define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'expert/index' + location.search,
                    add_url: 'expert/add',
                    edit_url: 'expert/edit',
                    del_url: 'expert/del',
                    multi_url: 'expert/multi',
                    import_url: 'expert/import',
                    import_excel: 'expert/import_excel',
                    table: 'expert',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                search: false,
                uniqueId: "id",
                fixedRightNumber: 1,
                maintainSelected: true,
                pageSize: 10,
                pageList: [10, 25, 50, 100, "All"],
                columns: [
                    [
                        { checkbox: true }, 
                        { field: 'rownum', title: "序号", operate: false},
                        { field: 'name', title: __('Name'), operate: 'LIKE' },
                        { field: 'professional', title: __('Professional'), operate: 'LIKE' },
                        { field: 'position', title: __('Position'), operate: 'LIKE', searchList: position },
                        { field: 'expert_data', title: "专家库", operate: 'LIKE', table: table, class: 'autocontent', searchList: expert_data },
                        { field: 'work_unit', title: __('Work_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content },
                        { field: 'contact_tel', title: __('Contact_tel'), operate: 'LIKE' },
                        { field: 'area', title: __('Address'), formatter: function (e1, e) { return e.province + '-' + e.city + '-' + e.area; }, operate: 'LIKE', searchList: function (column) { return Template('sourcetpl', {}); } },
                        { field: 'sex', title: __('Sex'), searchList: { "1": "男", "2": "女" }, formatter: Table.api.formatter.label },
                        { field: 'createtime', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'updatetime', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                    ]
                ],
                //表格通用搜索渲染完成后触发
                onPostCommonSearch: function () {
                    var form = $("form", table.$commonsearch);
                    $("input[name='professional']", form).addClass("selectpage")
                        .data("source", "expert/searchProfessional")
                        .data("primaryKey", "id")
                        .data("field", "name")
                        .data("orderBy", "id desc")
                        .data('pagination', true)
                        .data("pageSize", 10);
                    Form.events.cxselect(form);
                    Form.events.selectpage(form);
                },
            });

            $('#table').on('check-all.bs.table', function (e, $row, $element) {

                for (let i = 0; i < $row.length; i++) {
                    $('#table1').bootstrapTable('removeByUniqueId', $row[i]['id']);
                    $('#table1').bootstrapTable('append', $row[i]);
                }

            })
            $('#table').on('uncheck-all.bs.table', function (e, $row, $element) {
                $('#table1').bootstrapTable('removeAll');
            })
            $('#table').on('check.bs.table', function (e, $row, $element) {
                $('#table1').bootstrapTable('removeByUniqueId', $row.id);
                $('#table1').bootstrapTable('append', $row);
            })
            $('#table').on('uncheck.bs.table', function (e, $row, $element) {
                $('#table1').bootstrapTable('removeByUniqueId', $row.id);
            })
            $('#table').on('load-success.bs.table', function (data) {

                var rowsData = $('#table').bootstrapTable('getData') ? $('#table').bootstrapTable('getData') : [];
                var rowsData1 = $('#table1').bootstrapTable('getData') ? $('#table1').bootstrapTable('getData') : [];
                var expert_ids = [];//$("#expert_ids").val();
                // if (expert_ids) {
                //     expert_ids = expert_ids.split(',');
                // } else {
                //     expert_ids = []
                // }
                // debugger

                // rowsData.forEach((item, targetRowIndex)=>{
                //     debugger
                //     var targetRowIndex = expert_ids.findIndex(row => row == item.id); 
                //     if (targetRowIndex != -1) { 
                //         $('#table1').bootstrapTable('removeByUniqueId', rowsData[targetRowIndex]['id']);
                //         $('#table1').bootstrapTable('append', rowsData[targetRowIndex]);
                //         $('#table').bootstrapTable('check', targetRowIndex); 
                //     } else {
                //         $('#table').bootstrapTable('uncheck', targetRowIndex); 
                //     }
                // })


                if (rowsData1.length > 0) {
                    expert_ids = rowsData1.map((item) => item.id);
                }
                expert_ids.forEach((item) => {
                    var targetRowIndex = rowsData.findIndex(row => row.id == item);
                    if (targetRowIndex != -1) {
                        $('#table1').bootstrapTable('removeByUniqueId', rowsData[targetRowIndex]['id']);
                        $('#table1').bootstrapTable('append', rowsData[targetRowIndex]);
                        $('#table').bootstrapTable('check', targetRowIndex);
                    }
                })
            });



            // 获取选中项
            // $(document).on("click", ".btn-selected", function () {
            //     let originalArray = Table.api.selecteddata(table);
            //     const ids = originalArray.map(item => item.id);

            //     let project_id = $("#project_id").val()
            //     Fast.api.close({ ids: ids, project_id: project_id });
            // });


            /////////////////////////////////////////////////////////////////
            $(toolbar2).on('click', Table.config.btn_qdsc, function () {
                let allRow = $('#table1').bootstrapTable('getData');
                if (allRow.length <= 0) {
                    Toastr.error("请选择专家");
                    return;
                }
                let project_id = $("#project_id").val()
                var temp_project = []
                for (let i = 0; i < allRow.length; i++) {
                    temp_project.push(allRow[i]['id'])
                }

                $.ajax({
                    type: "POST",
                    url: 'project/upload_expert',
                    dataType: 'json',
                    data: { ids: temp_project, pid: project_id },
                    success: function (response) {
                        if (response.code == 1) {
                            Toastr.success("上传成功");
                            setTimeout(() => {
                                Fast.api.close({ result: true });
                            }, 1000);
                        } else {
                            Toastr.error(response.msg);
                            return false;
                        }
                    },
                    error: function (xhr, status, error) {
                    }
                });

            });
            var table1 = $("#table1");
            // 初始化表格
            table1.bootstrapTable({
                extend: {
                    index_url: '',
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    btn_qdsc: '',
                    table: '',
                },
                showToggle: false,
                toolbar: '#toolbar2',
                showColumns: false,
                showExport: false,
                searchFormVisible: false,
                search: false,
                showSearch: false,
                pagination: false,
                showFooter: false,
                showPaginationSwitch: false,
                uniqueId: "id",
                columns: [
                    [
                        { field: 'id', title: __('Id') },
                        { field: 'name', title: "专家名称" },
                        {
                            field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, buttons: [
                                {
                                    name: 'delete',
                                    title: '删除',
                                    text: '删除',
                                    classname: 'btn btn-danger btn-xs btn-click',
                                    click: function (e, data) {
                                        $('#table1').bootstrapTable('removeByUniqueId', data.id);

                                        var rowsData = $('#table').bootstrapTable('getData');
                                        var targetRowIndex = rowsData.findIndex(row => row.id === data.id);
                                        if (targetRowIndex != -1) {
                                            $('#table').bootstrapTable('uncheck', targetRowIndex);
                                        }
                                    }
                                }
                            ], formatter: Table.api.formatter.operate
                        }
                    ]
                ],
            });
            ///////////////////////////////////////////////////////////

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'expert/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'name', title: __('Name'), align: 'left' },
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'expert/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'expert/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});

function aaa(e) {
    $(e).removeAttr('name');
}